package com.polaris.live.ui.game

import android.app.Activity
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.view.KeyEvent
import android.view.WindowManager
import com.gyf.immersionbar.ImmersionBar
import com.lxj.xpopup.XPopup
import com.polaris.live.R
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.mvvm.base2.BaseVbActivity
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.databinding.ActivityGameWebBinding
import com.polaris.live.floating.FloatingWindowManager
import com.polaris.live.im.manager.ImNoticeManager
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.popup.party.CloseGamePopup
import com.polaris.live.resp.back_resp.GameVo
import com.polaris.live.resp.bean.GameExtBean
import com.polaris.live.resp.bean.YomiGameExtBean
import me.jessyan.autosize.AutoSizeConfig
import me.jessyan.autosize.onAdaptListener
import me.jessyan.autosize.utils.ScreenUtils

/**
 * WebGameActivity 游戏web
 * @author Created by 天晴 on 2024/1/15 9:43
 * @since 1.0.0
 */
class WebGameActivity : BaseVbActivity<BaseViewModel, ActivityGameWebBinding>() {

    private val gameVo: GameVo? by lazy {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            intent.getParcelableExtra("gameVo", GameVo::class.java)
        } else {
            intent.getParcelableExtra("gameVo")
        }
    }
    private val gameMode: String by lazy {
        intent.getStringExtra("gameMode") ?: GameUtils.FULL_SCREEN
    }
    private val roomId: String by lazy {
        intent.getStringExtra("roomId") ?: ""
    }

    private val extBean: GameExtBean? by lazy {
        gameVo?.ext?.let { JsonUtils.fromJson(it, GameExtBean::class.java) }
    }

    private val yomiExtBean: YomiGameExtBean? by lazy {
        gameVo?.ext?.let { JsonUtils.fromJson(it, YomiGameExtBean::class.java) }
    }

    override fun initImmersionBar() {
        if (isHalfWindow()) {
            ImmersionBar.with(this)
                .statusBarColor(R.color.black)
                .navigationBarColor(R.color.color_fa1d1928)
                .titleBarMarginTop(mBinding.llContent)
                .init()
        } else {
            ImmersionBar.with(this)
                .apply {
                    if (isTransparentTop()) {
                        statusBarDarkFont(false)
                    } else {
                        statusBarColor(R.color.black)
                        titleBarMarginTop(mBinding.llContent)
                    }

                    if (isTransparentBottom()) {
                        transparentNavigationBar()
                    } else {
                        navigationBarColor(R.color.color_fa1d1928)
                    }
                }
                .init()
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

        AutoSizeConfig.getInstance().onAdaptListener = object : onAdaptListener {
            override fun onAdaptBefore(target: Any?, activity: Activity) {
                ScreenUtils.getScreenSize(activity).apply {
                    AutoSizeConfig.getInstance().screenWidth = this[0]
                    AutoSizeConfig.getInstance().screenHeight = this[1]
                }
                //根据屏幕方向，设置适配基准
                if (activity.resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    //设置横屏基准
                    AutoSizeConfig.getInstance().designWidthInDp = 812
                } else {
                    //设置竖屏基准
                    AutoSizeConfig.getInstance().designWidthInDp = 375
                }
            }

            override fun onAdaptAfter(target: Any?, activity: Activity?) {
            }
        }

        GameUtils.start()
        requestedOrientation = if (isHorizontal()) {
            ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE

        } else {
            ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        }
        gameVo?.let {
            mBinding.gameView.initWeb(this, it, gameMode, roomId,
                recharge = {
                    showRecharge()
                },
                destroy = {
                    if (isYomiGame(it.providerType)) {
                        finish()
                    } else {
                        if ((isHalfWindow() && isHasHalfWindow()) || (!isHalfWindow() && isHasAllWindow())) {
                            showPop()
                        } else {
                            finish()
                        }
                    }
                })
        }
        //余额变动
        ImNoticeManager.observeAccountChange(this) {
            mBinding.gameView.walletUpdate(UserManager.getUserId())
            UserManager.getUser().account?.userCoins?.let { mBinding.gameView.onBalanceUpdate(it) }
        }
    }

    private fun showRecharge() {
        GlobalPopupManager.showRechargePopup(
            this,
            mViewModel,
            isNeedBottom = false,
            onRechargeOk = { re ->
                if (re == true) {
                    mBinding.gameView.walletUpdate(UserManager.getUserId())
                    UserManager.getUser().account?.userCoins?.let { mBinding.gameView.onBalanceUpdate(it) }
                }
            }
        )
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        return mBinding.gameView.mAgentWeb?.handleKeyEvent(
            keyCode,
            event
        ) == true || super.onKeyDown(keyCode, event)
    }

    override fun onBackPressed() {
        showPop()
    }

    private fun showPop() {
        XPopup.Builder(this)
            .navigationBarColor(R.color.color_fa1d1928)
            .isDestroyOnDismiss(true)
            .asCustom(
                CloseGamePopup(
                    this,
                    gameVo?.exitExplain ?: "",
                    cancel = {

                    },
                    ok = {
                        finish()
                    })
            )
            .show()
    }

    private fun isHalfWindow() = gameMode == GameUtils.HALF_SCREEN || gameMode == GameUtils.HALF_SCREEN2

    private fun isTransparentTop() = extBean?.transparentTop == true || yomiExtBean?.transparentTop == true

    private fun isTransparentBottom() = extBean?.transparentBottom == true || yomiExtBean?.transparentBottom == true

    private fun isHorizontal() = extBean?.horizontal == 1 || yomiExtBean?.horizontal == 1

    private fun isHasHalfWindow() = extBean?.hasHalfWindow == 1 || yomiExtBean?.hasHalfWindow == 1

    private fun isHasAllWindow() = extBean?.hasAllWindow == 1 || yomiExtBean?.hasAllWindow == 1

    private fun isYomiGame(providerType: Long) = providerType == AppConst.GameType.YOMI

    override fun onPause() {
        mBinding.gameView.onPause()
        super.onPause()
    }

    override fun onResume() {
        mBinding.gameView.onResume()
        if (extBean?.horizontal == 1) {
            FloatingWindowManager.updateOrientation(1)
        }
        super.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        GameUtils.finish()
        mBinding.gameView.onDestroy()
        FloatingWindowManager.updateOrientation(0)
    }
}